package com.chen.palmar.project.home;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.CommentRequest;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.common.widget.view.DrawableCenterTextView;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.GoodEntity;
import com.chen.palmar.entity.HomeListEntity;
import com.chen.palmar.entity.TagListEntity;
import com.primb.androidlibs.net.entity.HttpResultEntity;
import com.primb.androidlibs.net.exception.ApiException;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

import static com.mob.MobSDK.getContext;

/**
 * @author Chen
 * @date 2018/1/3
 * 功能描述：供应信息
 */

public class SupplyActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.iv_top)
    ImageView ivTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.et_search)
    DrawableCenterTextView etSearch;
    @Bind(R.id.rv_content)
    RecyclerView rvContent;
    @Bind(R.id.rv_menu)
    RecyclerView rvMenu;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.swipe_supply)
    SwipeRefreshLayout swipeSupply;
    @Bind(R.id.tv_top)
    TextView tvTop;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private BaseQuickAdapter<HomeListEntity.DataBean, BaseViewHolder> adapter;
    private int page = 0;
    private int pageSize = 10;
    private List<HomeListEntity.DataBean> dataList = new ArrayList<>();
    private String labelId = "";
    private BaseQuickAdapter<TagListEntity.DataBean, BaseViewHolder> adapterMenu;
    private String info;
    private SparseArray<Boolean> selectList = new SparseArray<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_supply;
    }

    @Override
    public void init() {

        info = getIntent().getStringExtra("info");

        if ("1".equals(info)) {
            titleBar.setText("供应信息");
        } else {
            titleBar.setText("采购信息");
        }
        toolBar.setNavigationOnClickListener(v -> SupplyActivity.this.finish());

        try {
            getListData(false);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
            swipeSupply.setRefreshing(false);
        }

        swipeSupply.setOnRefreshListener(() -> {
            try {
                getListData(false);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                swipeSupply.setRefreshing(false);
            }
        });

        rvContent.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        Glide.with(SupplyActivity.this).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        Glide.with(SupplyActivity.this).resumeRequests();
                        break;
                }
            }
        });

        swipeSupply.setColorSchemeColors(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright), ContextCompat.getColor(getContext(), android.R.color.holo_green_light), ContextCompat.getColor(getContext(), android.R.color.holo_orange_light), ContextCompat.getColor(getContext(), android.R.color.holo_red_light));

        //开关指示器，必须是drawer的监听器
        //扩展该监听器以监听事件自身
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // 更新选项菜单
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged(newState);
                supportInvalidateOptionsMenu();
            }
        };
        //为侧滑菜单绑定监听器
        drawerLayout.addDrawerListener(actionBarDrawerToggle);

        ivTop.setVisibility(View.GONE);
        tvTop.setVisibility(View.VISIBLE);
        ivTop.setImageResource(R.mipmap.supply_select_icon);
        tvTop.setText("筛选");
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.supply_select_icon);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        tvTop.setCompoundDrawables(null, null, drawable, null);
        tvTop.setCompoundDrawablePadding(1);

        rvContent.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvContent.setLayoutManager(linearLayoutManager);
        rvContent.setItemAnimator(new DefaultItemAnimator());
        adapter = new BaseQuickAdapter<HomeListEntity.DataBean, BaseViewHolder>(R.layout.item_home) {
            @Override
            protected void convert(BaseViewHolder helper, HomeListEntity.DataBean item) {
                helper.setText(R.id.tv_item_home_content, item.getContent());
                helper.setText(R.id.tv_item_home_good, item.getPraise_nums() + "");
                helper.setText(R.id.tv_item_home_watch, item.getBrowse_nums() + "");
                helper.setText(R.id.tv_item_home_location, item.getAddress_detail());
                helper.setText(R.id.tv_item_home_name, item.getUser_name());
                helper.setText(R.id.tv_item_date, item.getCreate_at());
                helper.setText(R.id.tv_item_home_comment, item.getComment_nums() + "");
                helper.setVisible(R.id.tv_item_home_state, false);
                helper.setVisible(R.id.tv_item_home_type, false);
                helper.setText(R.id.tv_item_home_type, "进口食品");
                helper.setVisible(R.id.tv_item_home_comment, true);
                helper.setVisible(R.id.iv_item_home_comment, true);

                helper.addOnClickListener(R.id.tv_item_home_good);
                helper.addOnClickListener(R.id.tv_item_home_comment);
                helper.addOnClickListener(R.id.iv_item_home_good);
                helper.addOnClickListener(R.id.iv_item_home_comment);

                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_home_head);
                Glide.with(getContext()).load(item.getUser_avatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
                RecyclerView rvImg = (RecyclerView) helper.getView(R.id.rv_item_home_img);
                rvImg.setNestedScrollingEnabled(false);
                GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                rvImg.setLayoutManager(layoutManager);
                BaseQuickAdapter<String, BaseViewHolder> adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_img) {
                    @Override
                    protected void convert(BaseViewHolder helper, String item) {
                        SquareImageView view = (SquareImageView) helper.getView(R.id.iv_item_img);
                        Glide.with(getContext()).load(item).override(AppConstant.SCREEN_WIDTH / 3, AppConstant.SCREEN_WIDTH / 3).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).fitCenter().into(view);
                    }
                };
                rvImg.setItemAnimator(new DefaultItemAnimator());
                adapterImg.setNewData(item.getImgList());
                rvImg.setAdapter(adapterImg);
            }
        };

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.tv_item_home_good:
                    case R.id.iv_item_home_good:
                        goodInfo(((HomeListEntity.DataBean) adapter.getData().get(position)).getArticleId() + "", position);
                        break;
                    case R.id.iv_item_home_comment:
                    case R.id.tv_item_home_comment:
                        commentInfo(((HomeListEntity.DataBean) adapter.getData().get(position)).getArticleId() + "", position);
                        break;
                }
            }
        });
        adapter.setOnLoadMoreListener(() -> {
            page += 1;
            getListData(true);
        }, rvContent);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), InfoDetailActivity.class);
            intent.putExtra("info", adapter.getData().get(position).getArticleId() + "");
            startActivity(intent);
        });
        rvContent.setAdapter(adapter);

        getTagList();

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMenu.setLayoutManager(layoutManager);
        rvMenu.setItemAnimator(new DefaultItemAnimator());

        adapterMenu = new BaseQuickAdapter<TagListEntity.DataBean, BaseViewHolder>(R.layout.item_supply_tag) {
            @Override
            protected void convert(BaseViewHolder helper, TagListEntity.DataBean item) {
                helper.setText(R.id.iv_item_supply_tag, item.toString());
                CheckBox box = (CheckBox) helper.getView(R.id.iv_item_supply_tag);
                if (selectList.get(helper.getAdapterPosition())) {
                    box.setChecked(true);
                    box.setTextColor(ContextCompat.getColor(SupplyActivity.this, R.color.colorPrimaryDark));
                } else {
                    box.setTextColor(ContextCompat.getColor(SupplyActivity.this, R.color.app_font));
                    box.setChecked(false);
                }
            }
        };
        adapterMenu.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < selectList.size(); i++) {
                    if (position == i && !selectList.get(position)) {
                        selectList.put(i, true);
                    } else {
                        selectList.put(i, false);
                    }
                }
                if (!selectList.get(position)) {
                    labelId = "";
                } else {
                    labelId = adapterMenu.getData().get(position).getLabelId() + "";
                }
                adapterMenu.notifyDataSetChanged();
            }
        });
        rvMenu.setAdapter(adapterMenu);

    }

    /**
     * 评论
     */
    private void commentInfo(String id, int position) {
        CommentRequest.commentInfo(this, getSupportFragmentManager(), id, "1", new CommentRequest.OnLoadSuccessListener<HttpResultEntity>() {
            @Override
            public void onSuccess(HttpResultEntity entity) {
                showToast(entity.getMessage());
                int nums = adapter.getData().get(position).getComment_nums();
                nums += 1;
                adapter.getData().get(position).setComment_nums(nums);
                adapter.notifyItemChanged(position);
            }

            @Override
            public void onFailure(ApiException e) {

            }
        });
    }

    /**
     * 点赞
     */
    private void goodInfo(String id, int position) {
        CommentRequest.goodInfo(id, new CommentRequest.OnLoadSuccessListener<GoodEntity>() {
            @Override
            public void onSuccess(GoodEntity entity) {
                showToast(entity.getMessage());
                int nums = adapter.getData().get(position).getPraise_nums();
                if (entity.getData().getStatus() == 1) {
                    nums += 1;
                } else {
                    nums -= 1;
                }
                adapter.getData().get(position).setPraise_nums(nums);
                adapter.notifyItemChanged(position);
            }

            @Override
            public void onFailure(ApiException e) {

            }
        });
    }

    private void getTagList() {
        Subscription subscribe = DataCenter.tagListInfo().subscribe(new HttpSubscriber<TagListEntity>(this, null) {
            @Override
            public void onNext(TagListEntity tagListEntity) {
                for (int i = 0; i < tagListEntity.getData().size(); i++) {
                    selectList.put(i, false);
                }
                adapterMenu.setNewData(tagListEntity.getData());
            }
        });
        subscription.add(subscribe);
    }

    /**
     * 数据动态列表
     */
    private void getListData(boolean isLoad) {
        if (!isLoad) {
            swipeSupply.setRefreshing(true);
            page = 0;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("articleType", info);
        map.put("labelId", labelId);
        map.put("page", page + "");
        map.put("page_size", pageSize + "");
        Subscription listSub = DataCenter.homeListInfo(map).subscribe(new HttpSubscriber<HomeListEntity>(getContext(), null) {
            @Override
            public void onNext(HomeListEntity homeEntity) {
                if (!isLoad) {
                    dataList.clear();
                    dataList.addAll(homeEntity.getData());
                    adapter.setNewData(dataList);
                    if (dataList.size() < pageSize) {
                        adapter.loadMoreEnd();
                    } else {
                        adapter.loadMoreComplete();
                    }
                    if (dataList.size() == 0) {
                        showToast("暂无数据");
                    }
                } else {
                    dataList.addAll(homeEntity.getData());
                    adapter.addData(dataList);
                    if (homeEntity.getData().size() < pageSize) {
                        adapter.loadMoreEnd();
                    } else {
                        adapter.loadMoreComplete();
                    }
                }
                swipeSupply.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                swipeSupply.setRefreshing(false);
                if (isLoad) {
                    page -= 1;
                } else {
                    page = 0;
                }
            }
        });
        subscription.add(listSub);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //在更改任意配置时更新状态
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        //在框架还原任意实例状态之后同步Drawer的状态
        actionBarDrawerToggle.syncState();
    }

    @OnClick({R.id.tv_supply_cancel, R.id.tv_supply_sure, R.id.tv_top, R.id.et_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top:
                if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    drawerLayout.post(() -> drawerLayout.closeDrawers());
                } else {
                    drawerLayout.post(() -> drawerLayout.openDrawer(Gravity.RIGHT));
                }
                break;
            case R.id.tv_supply_cancel:
                drawerLayout.post(() -> drawerLayout.closeDrawers());
                break;
            case R.id.tv_supply_sure:
                getListData(false);
                drawerLayout.post(() -> drawerLayout.closeDrawers());
                break;
            case R.id.et_search:
                Intent intent = new Intent(getContext(), SearchListActivity.class);
                if ("1".equals(info)) {
                    //供应
                    intent.putExtra("info", SearchListActivity.REQUEST_CODE_SUPPLY);
                } else {
                    //采购
                    intent.putExtra("info", SearchListActivity.REQUEST_CODE_PURCHASE);
                }
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
